package com.zmz.juc.forkjoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * 用fork(),join()写阶乘
 */
public class FactorialCalculator extends RecursiveTask<Long> {
    private final int n;

    public FactorialCalculator(int n) {
        this.n = n;
    }

    @Override
    protected Long compute() {
        if (n <= 1) {
            return (long) 1;
        } else {
            FactorialCalculator subtask = new FactorialCalculator(n - 1);
            //通过fork（）来拆分子任务,子任务再执行compute计算递归
            subtask.fork();

            //通过join拿到子任务的计算结果并计算返货

            return n * subtask.join();
        }

    }

    public static void main(String[] args) {
        int n = 4; // 输入阶乘数

        ForkJoinPool pool = ForkJoinPool.commonPool(); // 创建Fork-Join池

        long result = pool.invoke(new FactorialCalculator(n)); // 启动任务计算

        System.out.println("Factorial(" + n + ") = " + result);
    }

}
